﻿using System;
using System.Configuration;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;
using Microsoft.Extensions.DependencyInjection;

namespace myweb.Models
{
    public class MyWebDbContext : DbContext
    {
        private static MyWebDbContext _myWebDbContext;
        private static IConfiguration _configuration;
        public MyWebDbContext(DbContextOptions<MyWebDbContext> options)
            : base(options)
        {

        }
        /// <summary>
        /// DbSet实体集属性对应数据库中的表(注意实体集名必须与表明一致)
        /// </summary>
        public DbSet<UserInfo> UserInfos { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserInfo>().ToTable("t_userinfo");
        }

        public static MyWebDbContext getInstance()
        {
            if (_myWebDbContext != null)
            {
                return _myWebDbContext;
            }
            else
            {
                if (_configuration == null)
                {
                    _configuration = new ConfigurationBuilder()
                        .SetBasePath(AppDomain.CurrentDomain.BaseDirectory)
                        .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
                        .Build();
                }
             
                var connString = _configuration.GetSection("ConnectionStrings:DefaultConnection").Value;

                var options = new DbContextOptionsBuilder<MyWebDbContext>()
                    .UseMySQL(@connString).Options;
                _myWebDbContext = new MyWebDbContext(options);
                return _myWebDbContext;
            }

        }
    }
}
